﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Program11
{
    /// <summary>
    /// 加密类
    /// </summary>
    public class Encryption
    {
        public static string GetMd5(string str)
        {
            var md5 = MD5.Create();

            //将字符转化成一个二进制数组
            var bitArray = Encoding.GetEncoding("UTF-8").GetBytes(str);
            //进行加密
            var md5BitArray = md5.ComputeHash(bitArray);

            var encryptStr = "";
            for(var i = 0; i < md5BitArray.Length; i++)
            {
                encryptStr += md5BitArray[i].ToString("x2");

            }
            md5.Clear();
            return encryptStr;
        }

        public static string GetSHAMD5(string str)
        {
            var sHA = SHA512.Create();
            var md5 = MD5.Create();
            //将字符转化成一个二进制数组
            var bitArray = Encoding.GetEncoding("UTF-8").GetBytes(str+"@j56Yk./@0Dfg");
            //进行加密
            var md5BitArray = md5.ComputeHash(bitArray);
            var sHABitArray = sHA.ComputeHash(md5BitArray);

            var encryptStr = "";
            for (var i = 0; i < sHABitArray.Length; i++)
            {
                encryptStr += sHABitArray[i].ToString("x2");

            }
            sHA.Clear();
            return encryptStr;
        }

        //盐，模拟，实际情况由随机算法按每用户标识生成
        private static readonly byte[] SaltKeys =
        {
            0xfa, 0x5e, 0x65, 0x05, 0xaf, 0x77, 0xfe, 0x45, 0x95, 0xa0, 0x18, 0x65, 0x20, 0x65, 0x32, 0xff
        };

        /// <summary>
        /// 用md5一次加密，然后加盐后，用sha512二次加密
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetEncryptString(string str)
        {
            var md5 = MD5.Create();
            var sha512 = SHA512.Create();

            //将字符转换成二进制数组
            var bitArray = Encoding.GetEncoding("UTF-8").GetBytes(str);

            //进行二次加密
            var encryptArray = sha512.ComputeHash(md5.ComputeHash(bitArray).Concat(SaltKeys).ToArray());

            var encryptStr = "";
            for (var i = 0; i < encryptArray.Length; i++)
            {
                encryptStr += encryptArray[i].ToString("x2");
            }
            md5.Clear();
            sha512.Clear();

            return encryptStr;
        }

    }
}
